package com.plantplaces.dao;

import java.util.ArrayList;
import java.util.List;

import com.example.plantplacessummer2013.PlantPlacesActivity;
import com.plantplaces.dto.Plant;
import com.plantplaces.dto.PlantSearch;

/**
 * Gather plant data from online sources.
 * 
 * @author jonesbr
 *
 */
public class OnlinePlantDAO implements IPlantDAO {
	
	// class that does networking overhead.
	NetworkDAO networkDAO;
	
	public OnlinePlantDAO() {
		// instantiate class to do network overhead.
		networkDAO = new NetworkDAO();
		
	}

	@Override
	public List<Plant> fetchPlants(PlantSearch plantSearch) throws Exception {
		// Declare the collection that will hold our plants.
		ArrayList<Plant> allPlants = new ArrayList<Plant>();
		
		// assemble the query URL.
		
		// now we have a searchable URL.
		String url = PlantPlacesActivity.WEB_ROOT + "/perl/mobile/viewplants.pl?Combined_Name=" + plantSearch.getGenus();

		String result = networkDAO.request(url);
		
		// parse the result into the plant objects.
		String[] plantData = result.split("\n");
		
		// iterate over the plant data.  Break it into its components.
		for (String plantString : plantData) {
			// iterate over each plant string.  Parse it into its individual fields.
			String[] plantFields = plantString.split("\t");
			
			// create a new plant object.
			Plant thisPlant = new Plant();
			// populate that object.
			thisPlant.setGuid(Integer.parseInt(plantFields[0]));
			thisPlant.setGenus(plantFields[1]);
			thisPlant.setSpecies(plantFields[2]);
			thisPlant.setCultivar(plantFields[3]);
			thisPlant.setCommon(plantFields[4]);
			
			// add the populated plant to a collection.
			allPlants.add(thisPlant);
		}
		
		// TODO Auto-generated method stub
		return allPlants;
	}

	@Override
	public Plant fetchPlantByPlantPlacesId(int id) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
